﻿from flask_socketio import SocketIO, emit
import paramiko
import socketio

socketio = SocketIO()
name_space = '/dcenter'


class SSHProxy(object):
    def __init__(self, hostname, port, username, password):
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password
        self.transport = None
        self.event_name = 'dcenter'
        self.name_space = '/dcenter'

    def open(self):
        self.transport = paramiko.Transport((self.hostname, self.port))
        self.transport.connect(username=self.username, password=self.password)

    def command(self, cmd):
        xssh = paramiko.SSHClient()
        xssh._transport = self.transport
        stdin, stdout, stderr = xssh.exec_command(cmd)
        status = stdout.channel
        stdout = stdout
        code = status.recv_exit_status()
        result = (stdout.read().decode('utf-8'))
        res = {'code': code, 'result': result, 'stderr': stderr, 'stdout': stdout}
        return res
        # return result, stderr

    def push(self, result):
        print("result-line36:%s" % result)
        broad_ifo = []
        # for nodeinfo in allinfo:
        #     broad_ifo.append(
        #         {'uid': nodeinfo.task, 'text': nodeinfo.text, 'status': nodeinfo.status,
        #          'parent': nodeinfo.parent, 'servers': nodeinfo.servers})
        # socketio.emit(self.event_name, result, broadcast=True, namespace=self.name_space)
        socketio.emit(self.event_name, result, broadcast=True, namespace=self.name_space)

    def live(self, cmd):
        try:
            xssh = paramiko.SSHClient()
            xssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            xssh._transport = self.transport
            stdin, stdout, stderr = xssh.exec_command(cmd, timeout=3, get_pty=True)
            status = stdout.channel
            stdout = stdout
            while not stdout.channel.exit_status_ready():  # 循环条件为返回为 False
                result = stdout.readline()
                result = {"result": result, "status": status}
                self.push(result)
                if stdout.channel.exit_status_ready():
                    a = stdout.readlines()
                    break
        except Exception as e:
            print(e)

    def upload(self, local_path, remote_path):
        sftp = paramiko.SFTPClient.from_transport(self.transport)
        sftp.put(local_path, remote_path)
        sftp.close()

    def close(self):
        self.transport.close()

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


with SSHProxy('192.168.64.149', int(22), 'root', '123456') as ssh:
    # ssh.live('tcpdump -i ens33 -c 3')
    ssh.live('pwd')
    # result = ssh.command('pwd')
    # print(result)
